package com.my.ph.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Sets;
import com.my.ph.config.entity.UserJsonConfig;
import com.my.ph.entity.SysSetting;
import com.my.ph.service.SysSettingService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UserJsonConfigUtil {

    private static final Map<String, Object> defConfig = new HashMap<>(){{
        put("tmdbAPIKey", "");
        put("tmdbBaseUrl", "https://api.tmdb.org");
        put("torrentSavePath", "");
        put("torrentAnnounce", "");
        put("fileSavePath", "");
        put("defOperationType", "move");
        put("tmdbAdult", false);
        put("fileNameMovie", "{originalTitle}.{enTitle}.{year}.{videoFormat}.{source}.{videoCodec}.{audioCodec}.{audioNum}-{team}");
        put("fileNameTv", "{originalTitle}.{enTitle}.S{season}E{episode}.{year}.{videoFormat}.{source}.{videoCodec}.{audioCodec}.{audioNum}-{team}");
        put("folderNameTv", "{originalTitle}.{enTitle}.{year}.{videoFormat}.{source}.{videoCodec}.{audioCodec}.{audioNum}-{team}");
        put("folderNameTvSeason", "{originalTitle}.{enTitle}.S{season}.{year}.{videoFormat}.{source}.{videoCodec}.{audioCodec}.{audioNum}-{team}");
        put("folderNameTvSeasonEpisode", "{originalTitle}.{enTitle}.S{season}E{episode}.{year}.{videoFormat}.{source}.{videoCodec}.{audioCodec}.{audioNum}-{team}");
        put("mainTitleMovie", "{enTitle} {year} {videoFormat} {source} {videoCodec} {audioCodec} {channels} {audioNum}-{team}");
        put("mainTitleTv", "{enTitle} {year} {videoFormat} {source} {videoCodec} {audioCodec} {channels} {audioNum}-{team}");
        put("mainTitleTvSeason", "{enTitle} S{season} {year} {videoFormat} {source} {videoCodec} {audioCodec} {audioNum}-{team}");
        put("mainTitleTvSeasonEpisode", "{enTitle} S{season}E{episode} {year} {videoFormat} {source} {videoCodec} {audioCodec} {audioNum}-{team}");
        put("subTitleMovie", "{titles} | 类型：{genresName} | 演员：{actingName}");
        put("subTitleTv", "{titles} | 类型：{genresName} | 演员：{actingName}");
        put("subTitleTvSeason", "{titles} | {seasonName} | 类型：{genresName} | 演员：{actingName}");
        put("subTitleTvSeasonEpisode", "{titles} | {seasonName}{episodeName} | 类型：{genresName} | 演员：{actingName}");
        put("autoCreateSeasonFolder", true);
        put("source", Arrays.asList("WEB-DL", "Remux", "Blu-ray", "UHD Blu-ray", "Other", "Encode", "HDTV", "DVD", "CD", "Track", ""));
        put("team", Arrays.asList("WiKi","MySiLU","HDS","CHD","Other","rainweb","rain","StarfallWeb","AGSVWEB","Starfall",""));
        put("autoFeedLink", "https://xingyunge.top/upload.php#separator#name#linkstr#{主标题}#linkstr#small_descr#linkstr#{副标题}#linkstr#url#linkstr#{IMDB}#linkstr#dburl#linkstr#{豆瓣}#linkstr#descr#linkstr#{简介}[quote]{MediaInfo}[/quote]#linkstr#log_info#linkstr##linkstr#tracklist#linkstr##linkstr#music_type#linkstr##linkstr#music_media#linkstr##linkstr#edition_info#linkstr##linkstr#music_name#linkstr##linkstr#music_author#linkstr##linkstr#animate_info#linkstr##linkstr#anidb#linkstr##linkstr#torrentName#linkstr##linkstr#images#linkstr##linkstr#torrent_name#linkstr#{种子名称}#linkstr#torrent_url#linkstr#{种子链接}#linkstr#type#linkstr#{类型}#linkstr#source_sel#linkstr#{地区}#linkstr#standard_sel#linkstr#{分辨率}#linkstr#audiocodec_sel#linkstr#{音频编码}#linkstr#codec_sel#linkstr#{视频编码}#linkstr#medium_sel#linkstr#{媒介}#linkstr#origin_site#linkstr#{小组}#linkstr#origin_url#linkstr##linkstr#golden_torrent#linkstr#false#linkstr#mediainfo_cmct#linkstr##linkstr#imgs_cmct#linkstr##linkstr#full_mediainfo#linkstr##linkstr#subtitles#linkstr##linkstr#youtube_url#linkstr##linkstr#ptp_poster#linkstr##linkstr#comparisons#linkstr##linkstr#version_info#linkstr##linkstr#multi_mediainfo#linkstr##linkstr#labels#linkstr#0");
        put("videoFormatList", Arrays.asList("MP4","MKV","AVI","RMVB","WMV","TS","MOV","FLV","RM","3GP","WEBM","M4V","M4A"));
    }};
    private static UserJsonConfig userJsonConfig;
    private static SysSettingService settingService;
    private static ResourceLoader resourceLoader;

    @Autowired
    public void setResourceLoader(ResourceLoader resourceLoader) {
        UserJsonConfigUtil.resourceLoader = resourceLoader;
    }

    @Autowired
    public void setSettingService(SysSettingService settingService) {
        UserJsonConfigUtil.settingService = settingService;
    }

    public static UserJsonConfig getInstance() {
        return userJsonConfig;
    }

    @PostConstruct
    public void init() {
        Map<String, Object> map = settingService.list().stream().collect(Collectors.toMap(SysSetting::getSettingKey, SysSetting::getSettingValue));
        Set<String> differenceSet = Sets.difference(defConfig.keySet(), map.keySet());
        if (CollectionUtil.isNotEmpty(differenceSet)) {
            settingService.saveBatch(differenceSet.stream().map(key -> SysSetting.builder().settingKey(key).settingValue(StrUtil.toString(defConfig.get(key))).build()).toList());
        }
        userJsonConfig = JSONUtil.toBean(JSONUtil.parseObj(settingService.list().stream().collect(Collectors.toMap(SysSetting::getSettingKey, SysSetting::getSettingValue))),
                UserJsonConfig.class);
    }

    public static void update(UserJsonConfig jsonConfig) {
        Map<String, Long> idMap = settingService.list().stream().collect(Collectors.toMap(SysSetting::getSettingKey, SysSetting::getId));
        settingService.updateBatchById(BeanUtil.beanToMap(jsonConfig).entrySet().stream()
                .map(entry -> SysSetting.builder().id(idMap.get(entry.getKey())).settingKey(entry.getKey()).settingValue(StrUtil.toString(entry.getValue())).build()).toList());
        userJsonConfig = JSONUtil.toBean(JSONUtil.parseObj(settingService.list().stream().collect(Collectors.toMap(SysSetting::getSettingKey, SysSetting::getSettingValue))),
                UserJsonConfig.class);
    }

}
